//
//  MerchantHomeVC.m
//  dyseller
//
//  Created by 红喇叭 on 2017/12/5.
//  Copyright © 2017年 红喇叭. All rights reserved.
//

#import "MerchantHomeVC.h"
#import "XRDragTableView.h"
#import "MerchantCell.h"
#import "HLB_EditMerchatVC.h"
#import "HLBCoverPhotoVC.h"
#import "HLBShopMerchantVC.h"

@interface MerchantHomeVC ()<UITableViewDelegate,UITableViewDataSource>{
    BOOL _isEdit;
}

@property(nonatomic,strong)XRDragTableView *merchantTableView;
@property(nonatomic,strong)NSMutableArray *albumArray;

@end

@implementation MerchantHomeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavTitle:@"商家相册分类" titleColor:kBlackColor font:font17];
    [self.view addSubview:self.merchantTableView];
    
    
    [self rightNavItem];

   
    
    [self addBottomView];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //获取相册列表
    [self getAlbumList];
}


- (void)rightNavItem{
    
    __weak typeof (self)weakself = self;
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightBtn setTitle:@"管理" forState:UIControlStateNormal];
    [rightBtn setTitle:@"保存" forState:UIControlStateSelected];
    rightBtn.titleLabel.font = font17;
    [rightBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    [rightBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^(UIButton* sender) {
        sender.selected = !sender.selected;
        _isEdit = !_isEdit;
       
        if(_isEdit){
            weakself.merchantTableView.tableHeaderView = [self getHeaderView];
        }else{
            weakself.merchantTableView.tableHeaderView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 0.1)];
            [weakself saveAlbumSort];
        }
        [weakself.merchantTableView reloadData];
    }];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
}

#pragma  mark ========懒加载========
- (XRDragTableView *)merchantTableView{
    if(_merchantTableView == nil){
        _merchantTableView = [[XRDragTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H-TabBarItemHeight-NavigationHeight+49-GETHEIGHT(100)) style:UITableViewStyleGrouped];
        _merchantTableView.dataSource = self;
        _merchantTableView.delegate = self;
        _merchantTableView.estimatedRowHeight = 60;
        _merchantTableView.isGroup = YES;
        _merchantTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 0.1)];
        [_merchantTableView registerClass:[MerchantCell class] forCellReuseIdentifier:@"MerchantCell"];
    }
    return _merchantTableView;
}

//添加头视图
- (UIView *)getHeaderView{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 30)];
    headView.backgroundColor = UIColorFromRGB(0xfa6381);
    UILabel *tsLab = [[UILabel alloc] init];
    tsLab.textColor  = kWhiteColor;
    tsLab.text = @"长按可拖动相册进行排序";
    tsLab.font = font15;
    tsLab.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:tsLab];
    tsLab.sd_layout.centerYEqualToView(headView).leftSpaceToView(headView, 0).rightSpaceToView(headView, 0).heightIs(20);
    return headView;
}

- (void)addBottomView{
    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_H-HLBTabHeight-GETHEIGHT(100)-NavigationHeight, SCREEN_W, GETHEIGHT(100))];
    UIButton *addbtton = [[UIButton alloc] init];
    [addbtton setImage:[UIImage imageNamed:@"photo_bg7_default"] forState:UIControlStateNormal];
    [bottomV addSubview:addbtton];
    [addbtton addTarget:self action:@selector(editPushController:) forControlEvents:UIControlEventTouchUpInside];
    addbtton.sd_layout.centerYEqualToView(bottomV).
    centerXEqualToView(bottomV).widthIs(GETWITH(50)).heightEqualToWidth();
    [self.view addSubview:bottomV];
}

- (void)editPushController:(UIButton *)sender{
    HLB_EditMerchatVC *vc = [HLB_EditMerchatVC new];
    vc.isNew = YES;
    if(sender.tag>0){
        vc.editDataModel = ((NSMutableArray *)_albumArray[sender.tag-1]).firstObject;
        vc.isNew = NO;
    }
    [self.navigationController pushViewController:vc animated:vc];
}


#pragma  mark ========网络请求========

-(void)getAlbumList{
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Album/albumList" isactive:YES parameter:@{} successBlock:^(PPHttpRequest *request, id responseObj) {
        _albumArray = @[].mutableCopy;
        [responseObj enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            HLBAlbumListModel *model = [HLBAlbumListModel yy_modelWithJSON:obj];
            NSMutableArray *array = @[model].mutableCopy;
            [_albumArray addObject:array];
        }];
        weakself.merchantTableView.dataArray = _albumArray;
        [weakself.merchantTableView reloadData];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
     [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];
}

- (void)getAlbumSetEnable:(UIButton *)sender{
    HLBAlbumListModel *model = ((NSMutableArray *)_albumArray[sender.tag]).firstObject;
    __weak typeof (self)weakself = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Album/albumSetEnable" isactive:YES parameter:@{@"album_ids":model.albumID,@"is_enable":[model.is_enable isEqualToString:@"0"]?@"1":@"0"} successBlock:^(PPHttpRequest *request, id responseObj) {
        model.is_enable = [model.is_enable isEqualToString:@"0"]?@"1":@"0";
        _albumArray[sender.tag][0] = model;
        [weakself.merchantTableView reloadSections:[NSIndexSet indexSetWithIndex:sender.tag] withRowAnimation:UITableViewRowAnimationNone];
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
         [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }];

}

- (void)saveAlbumSort{
    
    NSMutableArray *newarray = @[].mutableCopy;
    for (NSMutableArray*arry in _albumArray){
        [newarray addObject:arry.firstObject];
    }
    NSMutableArray *newSort = @[].mutableCopy;
    for(int i=0;i<newarray.count;i++){
        
        HLBAlbumListModel *model = newarray[i];
        NSData *data = [model yy_modelToJSONData];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSMutableDictionary *newdic = dic.mutableCopy;
        if(i>0){
            newdic[@"sort"] = [NSString stringWithFormat:@"%ld",_albumArray.count-i-1];
        }
        [newSort addObject:newdic];
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newSort options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    __weak typeof (self)weakSelf = self;
    [[PPHttpRequsetData shareInstance] requestStyle:Request_POST URL:@"/ShopApi/Album/albumSort" isactive:YES parameter:@{@"data":jsonStr} successBlock:^(PPHttpRequest *request,id responseObj) {
        
    } failBlock:^(PPHttpRequest *request, NSString *errMsg) {
        [weakSelf getAlbumList];
        [AlertUtils showToastWithMessage:errMsg inView:self.view hideAfterDelay:2.0 beIndeter:NO];
        
    }];

}

#pragma  mark ========UITableViewDatasource UITableViewDelegate========
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _albumArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MerchantCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MerchantCell" forIndexPath:indexPath];
    cell.dataModel = ((NSMutableArray *)_albumArray[indexPath.section]).firstObject;
        
    if(indexPath.section==0){
       cell.isEdit = NO;
       cell.rightLab.hidden = !_isEdit;
       cell.rightImg.hidden = NO;
        
    }else{
        cell.isEdit = _isEdit;
        cell.rightImg.hidden = _isEdit;
        cell.rightLab.hidden = YES;
        UILongPressGestureRecognizer *longGet = [[UILongPressGestureRecognizer alloc] initWithTarget:self.merchantTableView action:@selector(moveRow:)];
        [cell.contentView addGestureRecognizer:longGet];
        if(!_isEdit){
            cell.contentView.userInteractionEnabled = NO;
        }else{
            cell.contentView.userInteractionEnabled = YES;
        }
    }
   
    cell.editingBtn.tag = indexPath.section + 1;
    [cell.editingBtn addTarget:self action:@selector(editPushController:) forControlEvents:UIControlEventTouchUpInside];
    cell.operateBtn.tag = indexPath.section;
    [cell.operateBtn addTarget:self action:@selector(getAlbumSetEnable:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
   
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(!_isEdit && indexPath.section==0){
        HLBAlbumListModel *model = ((NSMutableArray *)_albumArray[indexPath.section]).firstObject;
        HLBCoverPhotoVC *vc = [HLBCoverPhotoVC new];
        vc.editDataModel = model;
        [self.navigationController pushViewController:vc animated:YES];
    }else if(!_isEdit){
        HLBShopMerchantVC *vc = [HLBShopMerchantVC new];
        vc.editDataModel = ((NSMutableArray *)_albumArray[indexPath.section]).firstObject;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
         [AlertUtils showToastWithMessage:@"编辑相册时不能查看相册图片！！" inView:self.view hideAfterDelay:2.0 beIndeter:NO];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if(section == 0) return 0.1;
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    CGFloat height = 15;
    if(section==0) height = 0.1;
    return [self viewInSection:height];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [self viewInSection:0.1];

}

- (UIView *)viewInSection:(CGFloat)height{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, height)];
    view.backgroundColor = ControllerColor;
    return view;
}

@end
